const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const path = require("path");
const app = express();
const tencentcloud = require("tencentcloud-sdk-nodejs-tts");
const TtsClient = tencentcloud.tts.v20190823.Client;
const port = 5050;
app.use(bodyParser.json());
app.use(cors()); // 允许跨域请求

const staticPath = path.resolve(__dirname, "../public");
//托管静态资源
app.use(express.static(staticPath));

// SecretId:AKIDQ0aK2nWE4onjXI5lRCFIRfxAGHSbdjEk
// SecretKey:fM7hO4iDcDzfDlOJDEBxZ5iPfA1DnO4j
const clientConfig = {
  // 腾讯云认证信息
  credential: {
    secretId: "AKIDQ0aK2nWE4onjXI5lRCFIRfxAGHSbdjEk",
    secretKey: "fM7hO4iDcDzfDlOJDEBxZ5iPfA1DnO4j",
  },
  // 产品地域
  region: "ap-shanghai",
  // 可选配置实例
  profile: {
    signMethod: "HmacSHA256", // 签名方法
    httpProfile: {
      reqMethod: "POST", // 请求方法
      reqTimeout: 30, // 请求超时时间，默认60s
    },
  },
};
// 实例化要请求产品的client对象,clientProfile是可选的
const client = new TtsClient(clientConfig);

// API 接口: 接收文本并返回音频文件
app.post("/synthesize", async (req, res) => {
  const params = {
    Text: req.body.text,
    SessionId: req.body.id,
  };
  client.TextToVoice(params).then(
    (data) => {
      console.log(data);
      res.status(200).send({
        status: "ok",
        msg: "请求成功",
        data: data,
        code: 200,
      });
    },
    (err) => {
      console.error("error", err);
      res.status(500).send({
        status: "error",
        msg: "请求失败",
        data: err,
        code: 500,
      });
    }
  );
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});
